package com.demo.practiceui.views.chart;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.view.View;

import androidx.annotation.Nullable;

/**
 * 柱状图 - 最基础的自定义View
 * 核心知识点：
 * 1. onMeasure() - 测量View尺寸
 * 2. onSizeChanged() - 获取实际尺寸并初始化
 * 3. canvas.drawRect() - 绘制矩形
 * 4. 数据归一化 - 将数据映射到绘制区域
 */
public class BarChartView extends View {

    // 数据源
    private float[] data = {50, 80, 30, 90, 60, 75, 45};
    private String[] labels = {"周一", "周二", "周三", "周四", "周五", "周六", "周日"};

    // 画笔
    private Paint barPaint;        // 柱状画笔
    private Paint textPaint;       // 文字画笔
    private Paint axisPaint;       // 坐标轴画笔

    // 尺寸相关
    private int width;
    private int height;
    private float barWidth;
    private float barSpacing;
    private float maxValue = 100f;  // 数据最大值

    // 边距
    private float paddingLeft = 70f;
    private float paddingBottom = 100f;
    private float paddingTop = 60f;
    private float paddingRight = 60f;

    public BarChartView(Context context) {
        this(context, null);
    }

    public BarChartView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public BarChartView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    /**
     * 初始化画笔
     */
    private void init() {
        // 柱状画笔
        barPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        barPaint.setColor(Color.parseColor("#4CAF50"));
        barPaint.setStyle(Paint.Style.FILL);

        // 文字画笔
        textPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        textPaint.setColor(Color.parseColor("#333333"));
        textPaint.setTextSize(32f);
        textPaint.setTextAlign(Paint.Align.CENTER);

        // 坐标轴画笔
        axisPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        axisPaint.setColor(Color.parseColor("#CCCCCC"));
        axisPaint.setStrokeWidth(2f);
        axisPaint.setStyle(Paint.Style.STROKE);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        // 处理wrap_content情况，给一个默认尺寸
        int width = MeasureSpec.getSize(widthMeasureSpec);
        int height = MeasureSpec.getSize(heightMeasureSpec);
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);

        if (widthMode == MeasureSpec.AT_MOST) {
            width = 800;  // 默认宽度
        }
        if (heightMode == MeasureSpec.AT_MOST) {
            height = 600;  // 默认高度
        }
        setMeasuredDimension(width, height);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        width = w;
        height = h;

        // 计算柱状图的宽度和间距
        float chartWidth = width - paddingLeft - paddingRight;
        barSpacing = chartWidth / (data.length * 2);  // 间距
        barWidth = barSpacing;  // 柱宽等于间距
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        // 1. 绘制坐标轴
        drawAxis(canvas);

        // 2. 绘制柱状图
        drawBars(canvas);

        // 3. 绘制标签
        drawLabels(canvas);
    }

    /**
     * 绘制坐标轴
     */
    private void drawAxis(Canvas canvas) {
        float chartHeight = height - paddingTop - paddingBottom;
        float baseLineY = paddingTop + chartHeight;  // 基线Y坐标

        // Y轴
        canvas.drawLine(paddingLeft, paddingTop, paddingLeft, baseLineY, axisPaint);

        // X轴
        canvas.drawLine(paddingLeft, baseLineY, width - paddingRight, baseLineY, axisPaint);

        // 绘制Y轴刻度和数值
        textPaint.setTextAlign(Paint.Align.RIGHT);
        int steps = 5;  // 5个刻度
        for (int i = 0; i <= steps; i++) {
            float value = maxValue * i / steps;
            float y = baseLineY - (chartHeight * i / steps);
            canvas.drawLine(paddingLeft - 10, y, paddingLeft, y, axisPaint);
            canvas.drawText(String.format("%.0f", value), paddingLeft - 20, y + 10, textPaint);
        }
    }

    /**
     * 绘制柱状图
     */
    private void drawBars(Canvas canvas) {
        float chartHeight = height - paddingTop - paddingBottom;
        float baseLineY = paddingTop + chartHeight;

        for (int i = 0; i < data.length; i++) {
            // 计算柱状图位置
            float left = paddingLeft + barSpacing + i * (barWidth + barSpacing);
            float right = left + barWidth;
            
            // 数据归一化：将数据值映射到柱高
            float barHeight = (data[i] / maxValue) * chartHeight;
            float top = baseLineY - barHeight;
            float bottom = baseLineY;

            // 绘制柱状矩形
            RectF rectF = new RectF(left, top, right, bottom);
            
            // 不同柱子不同颜色
            barPaint.setColor(getBarColor(i));
            canvas.drawRect(rectF, barPaint);

            // 在柱状图顶部绘制数值
            textPaint.setTextAlign(Paint.Align.CENTER);
            textPaint.setColor(Color.parseColor("#666666"));
            canvas.drawText(String.format("%.0f", data[i]), 
                    left + barWidth / 2, top - 15, textPaint);
        }
    }

    /**
     * 绘制标签
     */
    private void drawLabels(Canvas canvas) {
        float chartHeight = height - paddingTop - paddingBottom;
        float baseLineY = paddingTop + chartHeight;
        
        textPaint.setTextAlign(Paint.Align.CENTER);
        textPaint.setColor(Color.parseColor("#333333"));
        
        for (int i = 0; i < labels.length; i++) {
            float x = paddingLeft + barSpacing + i * (barWidth + barSpacing) + barWidth / 2;
            canvas.drawText(labels[i], x, baseLineY + 40, textPaint);
        }
    }

    /**
     * 获取柱状图颜色
     */
    private int getBarColor(int index) {
        int[] colors = {
                Color.parseColor("#FF5722"),
                Color.parseColor("#4CAF50"),
                Color.parseColor("#2196F3"),
                Color.parseColor("#FFC107"),
                Color.parseColor("#9C27B0"),
                Color.parseColor("#00BCD4"),
                Color.parseColor("#FF9800")
        };
        return colors[index % colors.length];
    }

    /**
     * 设置数据
     */
    public void setData(float[] data, String[] labels) {
        this.data = data;
        this.labels = labels;
        
        // 计算最大值
        maxValue = 0;
        for (float value : data) {
            if (value > maxValue) {
                maxValue = value;
            }
        }
        maxValue = (float) (Math.ceil(maxValue / 10) * 10);  // 向上取整到10的倍数
        
        invalidate();  // 触发重绘
    }
}

